package edu.zsl.controller;

import edu.zsl.pojo.Course;
import edu.zsl.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
public class CourseController {
    private final CourseService courseService;
    @Autowired
    public CourseController(CourseService courseService) {this.courseService = courseService;}
    @GetMapping("/coursepage")
    public String getCoursePage(){
        return "course";
    }

    //获得所有的课程
    @GetMapping("/courses")
    public String getAllCourses(Model model){
        List<Course> courses = courseService.getAllCourses();
        model.addAttribute("courses", courses);
        return "course";
    }
    //添加课程
    @GetMapping("/addcoursepage")
    public String addCoursePage(){
        return "addcourse";
    }
    //新增的课程保存到数据库，并重定向到courses页面
    @PostMapping("/addcourse")
    public String addCourse(Course course){
        courseService.insertCourse(course);
        return "redirect:/courses";
    }
    //更新课程页面
    @GetMapping("/updatecoursepage/{id}")
    public String updateCoursePage(@PathVariable Integer id, Model model){
        Course course = courseService.getCourseById(id);
        model.addAttribute("course", course);
        return "updatecourse";
    }
    //将更新后的表单数据保存到数据库，重定向到courses页面
    @PostMapping("/updatecourse")
    public String updateCourse(@ModelAttribute Course course){
        courseService.updateCourse(course);
        return "redirect:/courses";
    }
    //删除课程
    @GetMapping("/deletecourse/{id}")
    public String deleteCourseById(@PathVariable Integer id, Model model){
        courseService.deleteCourseById(id);
        return "redirect:/courses";
    }
    //查询某一课程的学生选课情况
    @GetMapping("/getCourseStudentDetailsPage/{id}")
    public String getCourseStudentDetails(@PathVariable("id") Integer id,Model model) {
        List<Course> courses = courseService.getCourseStudentDetails(id);
        model.addAttribute("courses", courses);
        return "courseStudentDetails";
    }

}
